package com.rdtravel.web;

import com.rdtravel.exceptions.TripsToImportInvalidException;
import com.rdtravel.jaxb.Trips;
import com.rdtravel.services.TripsService;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.transform.stream.StreamSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/trips")
class TripsController {
	private static final String REDIRECT_AFTER_IMPORT_VIEW = "redirect:/trips/imported";
	private final static String IMPORT_VIEW = "trips/import";
	private final static String IMPORTED_VIEW = "trips/imported";
	private final TripsService tripsService;
	private final Unmarshaller unmarshaller;

	@Autowired
	public TripsController(TripsService tripsService, Unmarshaller unmarshaller) {
		this.tripsService = tripsService;
		this.unmarshaller = unmarshaller;
	}

	@RequestMapping(value = "export", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody
	Trips exportToXML(HttpServletResponse response) {
		response.setHeader("Content-disposition",
				"attachment; filename=trips.xml");
		return new Trips(tripsService.findFutureTrips());
	}

	@RequestMapping(value = "import", method = RequestMethod.GET)
	public String importForm() {
		return IMPORT_VIEW;
	}

	@RequestMapping(value = "import", method = RequestMethod.POST)
	public ModelAndView importTrips(@RequestParam("file") Part part) {
		List<String> errors = new ArrayList<String>();
		try {
			Trips trips = (Trips) unmarshaller.unmarshal(new StreamSource(part
					.getInputStream()));
			tripsService.importTrips(trips.getTrips());
		} catch (TripsToImportInvalidException ex) {
			errors = ex.getErrors();
		} catch (Exception ex) {
			errors.add("Invalid file");
		}
		if (errors.isEmpty()) {
			return new ModelAndView(REDIRECT_AFTER_IMPORT_VIEW);
		} else {
			ModelAndView modelAndView = new ModelAndView(IMPORT_VIEW);
			modelAndView.addObject("errors", errors);
			return modelAndView;
		}
	}

	@RequestMapping(value = "imported", method = RequestMethod.GET)
	public String imported() {
		return IMPORTED_VIEW;
	}

}
